package text

import (
	"context"
	"fmt"
	"github.com/beherochuling/beesoft_api/app/helper/chat"
	"github.com/gogf/gf/v2/net/ghttp"
	"regexp"
)

var TaskStream taskStream

type taskStream struct{}

func (receiver *taskStream) Sse(ctx context.Context, r *ghttp.Request) {
	r.Response.Header().Set("Content-Type", "text/event-stream")
	r.Response.Header().Set("Cache-Control", "no-cache")
	r.Response.Header().Set("Connection", "keep-alive")

	err := chat.NewChat().
		Url("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions").
		ApiKey("sk-ed07f918b33d452c9e1861527174f5f5").
		Stream(func(content string) error {
			_, err := fmt.Fprintln(r.Response.Writer, content)
			if err != nil {
				fmt.Println("Error writing to response:", err)
				return err
			}

			r.Response.Flush()

			return nil
		})
	if err != nil {
		fmt.Println("chat error", err)
		return
	}

	for {
		select {
		case <-ctx.Done():
			fmt.Println("Client disconnected: Stream")
			return
		default:
		}
	}
}
func (receiver *taskStream) Stream(ctx context.Context, r *ghttp.Request) {
	r.Response.Header().Set("Content-Type", "text/plain")
	r.Response.Header().Set("Cache-Control", "no-cache")
	r.Response.Header().Set("Connection", "keep-alive")

	err := chat.NewChat().
		Url("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions").
		ApiKey("sk-ed07f918b33d452c9e1861527174f5f5").
		Stream(func(content string) error {
			pattern := `data: (.*?)\n`
			re := regexp.MustCompile(pattern)
			matches := re.FindStringSubmatch(content)

			if len(matches) > 1 {
				for _, match := range matches[1:] {
					_, err := fmt.Fprintln(r.Response.Writer, match)
					if err != nil {
						fmt.Println("Error writing to response:", err)
						return err
					}

					r.Response.Flush()
				}
			} else {
				fmt.Println("Stream No match found: ", content)
			}

			return nil
		})
	if err != nil {
		fmt.Println("chat error", err)
		return
	}

	for {
		select {
		case <-ctx.Done():
			fmt.Println("Client disconnected: Stream")
			return
		default:
		}
	}
}
